import React, { useRef, useState,useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-components';
import { useModel } from '@umijs/max';
import { Button,Avatar,Input } from 'antd';
import styles from './index.less';
import { actionGptMsg } from '@/services/demo/UserController';
import { LoadingOutlined } from '@ant-design/icons';
const { Search,TextArea } = Input;
const AccessPage: React.FC = () => {
  const { initialState, setInitialState }:any = useModel('@@initialState');
  const [plist, setPlist] = useState([]);
  const [sendload, setSendload] = useState(false);
  const [searchValue, setSearchValue] = useState('');  
  const scrollableDivRef = useRef<HTMLDivElement>(null);  

  
  useEffect(() => { 
    const _hmenu = JSON.parse(localStorage.getItem('gptHistoryList') as any) || [];
    if(_hmenu){
      _hmenu.map((_item:any)=>{
        if(_item.content == 'loading'){
          _item.content = '请求失败！';
        }
      });
      setPlist(_hmenu || []);
    }
   
  }, []);
  useEffect(()=>{
    console.log('useEffect for:', plist);  
    setTimeout(()=>{
      msgScrollToBotton();
    },500);
  // }, [plist.length]); 
  }, [sendload]); 
  const getImg = (value:any) => {
    return `http://test1.xhinkcar.cn/static/img/gpt/${value==2?'you':'gpt'}.png`
  };
  const onSearch = (value:any) => {
    if(!value.trim()) return;
    handleSearch(value);
  };
  const handleSearch = (value: string) => {  
    // console.log('Searching for:', value);  
    setSendload(true);
    const _list:any = plist,_newid = 'gpt_'+new Date().getTime()+'_type2';
    _list.push({id:'gpt_'+new Date().getTime(),type:2,content:value});
    _list.push({id:_newid,type:1,content:'loading'});
    setPlist(_list || []);
    localStorage.setItem('gptHistoryList',JSON.stringify(_list));
    setTimeout(()=>{
      setSearchValue('');
    },500);
    try {
      actionGptMsg({prompt:value}).then((res: any) => {
        console.log('===getProjectList==',res);
        const _list2:any = plist;
        if (res.status == 1) {
            _list2.map((_item:any)=>{
              if(_item.id == _newid){
                _item.content = res.data.content;
              }
            });
           
        }else{
            _list2.map((_item:any)=>{
              if(_item.id == _newid){
                _item.content = "请求失败！";
              }
            });
        }
        setPlist(_list2 || []);
        localStorage.setItem('gptHistoryList',JSON.stringify(_list2));
        setTimeout(()=>{
          setSendload(false);
        },500);
      });
    } catch (error) {
      const _list2:any = plist;
      _list2.map((_item:any)=>{
        if(_item.id == _newid){
          _item.content = "请求失败！";
        }
      });
      setPlist(_list2 || []);
      localStorage.setItem('gptHistoryList',JSON.stringify(_list2));
      setTimeout(()=>{
        setSendload(false);
      },500);
    }
    
   
  }; 
  const msgScrollToBotton = () => {  
    if (scrollableDivRef.current) {  
      scrollableDivRef.current.scrollTop = scrollableDivRef.current.scrollHeight;  
    }  
  };
  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {  
      setSearchValue(e.target.value);  
  }; 

  return (
    
     <div className="tc_gm_main">
      <div className="tc_gm_3">
        <div className=" tc_m_1" ref={scrollableDivRef} >
          {
            plist.length ? 
            plist.map((_item:any)=>{
              return (<div key={_item.id} className={ `tc_gm_2 ${_item.type == 1 ? 'tc_m_2':'tc_m_3'}`} >
                  {
                    _item.type == 1 && <img className={styles.tc_m_5} src={getImg(_item.type)} alt="Thinkcar" />
                  }
                  {
                    _item.content == 'loading' ?
                    <div className="tc_gm_1" ><LoadingOutlined /></div> :
                    <div className="tc_gm_1" dangerouslySetInnerHTML={{ __html: _item.content }} ></div>
                  }
                  {/* <div className="tc_gm_1" dangerouslySetInnerHTML={{ __html: _item.content == 'loading' ? <LoadingOutlined /> : _item.content }} ></div> */}
                  {
                    _item.type == 2 && <img className={styles.tc_m_5} src={getImg(_item.type)} alt="Thinkcar" />
                  }
              </div>)
            })
            :<div className={styles.tc_m_7}>暂无数据</div>
          }
           
        </div>
        <div className={styles.tc_m_6}>
        <TextArea 
          placeholder="输入提问内容"
          // enterButton="发送" 
          autoSize={{ minRows: 3, maxRows: 3 }}
          value={searchValue} 
          onChange={(e:any)=>{handleChange(e)}}   
          className={styles.tc_m_9}
          // onPressEnter={()=>{onSearch(searchValue)}}   
        />
      
        <Button className={styles.tc_m_8} type="primary" onClick={()=>{onSearch(searchValue)}}  loading={sendload} size="large">
           发送
          </Button>
        </div>
        </div>
     </div>
  );
};

export default AccessPage;
